import axios from 'axios'
import { useUserStore } from '@/store/modules/user'
import { baseURL } from '@/config'
const userStore = useUserStore()
const { token } = userStore
export const exportSet = (
  ids: number[],
  name = '采购单导出',
  url = '/supplier/order/export'
) => {
  axios
    .get(`${baseURL}${url}`, {
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      params: {
        ids,
      },
    })
    .then((response) => {
      // 直接处理blob数据，不检查content-type
      const blob = new Blob([response.data], {
        // 根据实际情况设置类型
        type: 'application/vnd.ms-excel;charset=utf-8',
      })

      // 创建下载链接
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `${name}.xls` // 设置下载文件名

      // 触发下载
      document.body.appendChild(link)
      link.click()

      // 清理
      setTimeout(() => {
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      }, 0)

      ElMessage.success('导出成功')
    })
    .catch((error) => {
      // 错误处理
      if (error.response?.data instanceof Blob) {
        // 如果错误响应是blob，读取错误信息
        const reader = new FileReader()
        reader.onload = () => {
          try {
            const errorData = JSON.parse(reader.result as string)
            ElMessage.error(errorData.message || '导出失败')
          } catch {
            ElMessage.error('导出失败')
          }
        }
        reader.readAsText(error.response.data)
      } else {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    })
}
